<script setup lang="ts">
import { formatDate } from '~/shared/utils/date.util';
import Toast from '~/components/ui/toast.vue';
import { MessageApi } from '~/shared/api/message.api';
useSeoMeta({
  title: 'iamcola\' message.',
});

type Message = { content: string, createdAt: string };

const text = ref('');
const messages = ref<Message[]>([]);
const showToast = ref(false);
const tip = ref('');

const total = ref(0);
const pageSize = ref(10);
const page = ref(1);
const onChangePage = async (_page: number) => {
  page.value = _page;
  await getMessageData();
  document.querySelector('#main')?.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

onNuxtReady(async () => {
  getMessageData();
  getMessageTotal();
});

const getMessageData = async () => {
  const data: Message[] = await useRequestGet(MessageApi.GET_MESSAGE, {
    page: page.value,
    pageSize: pageSize.value,
    target: 'message'
  });

  messages.value = data;
};

const getMessageTotal = async () => {
  const totalData = await useRequestGet<number>(MessageApi.TOTAL_MESSAGE, { target: 'message' });

  total.value = totalData;
};

const submitMessage = async () => {
  if (text.value.trim() === '') {
    tip.value = '请输入留言内容，谢谢！';
    showToast.value = true;
    return;
  }
  const data = await useRequestPost<Message[]>(
    MessageApi.CREATE_MESSAGE,
    {
      content: text.value,
      target: 'message'
    }
  ).catch(err => {
    tip.value = err.message;
    showToast.value = true;
  });
  if (data) {
    text.value = '';
    getMessageData();
  }
};
</script>

<template>
  <div class="pb-6">
    <Toast v-model="showToast">{{ tip }}</Toast>
    <div class="pb-6 mb-6 border-b border-b-neutral-300 border-dashed">
      <textarea
        v-model="text"
        class="p-2 rounded-md bg-neutral-950 resize-none w-full h-24 border border-neutral-300"
        maxlength="100"
      />
      <div class="text-right">
        <button
          class="px-4 py-2 mt-2 rounded-md text-sm bg-neutral-950 text-neutral-300 hover:bg-amber-700"
          @click="submitMessage"
        >提交留言</button>
      </div>
    </div>
    <div
      v-for="(item, idx) in messages"
      :key="idx"
      class="bg-neutral-950 p-4 rounded-md mb-4"
    >
      <div class="text-neutral-300">{{ item.content }}</div>
      <div class="flex items-center">
        <p class="text-neutral-400 text-sm flex-1 flex justify-end items-center mt-2">留言时间：{{ formatDate(item.createdAt) }}</p>
      </div>
    </div>
    <PageComp
      v-if="total > pageSize"
      :page="page"
      :page-size="pageSize"
      :total="total"
      @on-change="onChangePage"
    />
  </div>
</template>

<style lang="scss" scoped>
</style>